'use strict';
(function() {

    /**
     * angularjs的ng-repeat指令只识别数组
     */
    function _range(number) {
        console.info("userlogapgin._range....." + number);
        return new Array(number);
    }

    /**
     * 初始化翻页信息
     */
    function initShowPage($scope) {
        console.info("userlogapgin.initShowPage...");

        var showPageCnt = 7;
        var firstPage = 1;
        var lastPage = showPageCnt;

        var pagin = $scope.pagin;
        if (pagin.pageCnt <= showPageCnt) {
            lastPage = pagin.pageCnt;
            showPageCnt = pagin.pageCnt;

        } else {
            var isEven = showPageCnt % 2 == 0;
            firstPage = pagin.pageIndex - (parseInt(showPageCnt / 2) - (isEven ? 1 : 0));
            lastPage = pagin.pageIndex + parseInt(showPageCnt / 2);
            if (firstPage < 1) {
                lastPage += 1 - firstPage;
                firstPage = 1;
            } else if (lastPage > pagin.pageCnt) {
                firstPage -= lastPage - pagin.pageCnt;
                lastPage = pagin.pageCnt;
            }
        }

        $scope._baseCnt = firstPage;
        $scope._showPageCnt = showPageCnt;
    }

    /**
     * 翻页方法，过滤后再调用实际翻页方法
     */
    function _showPage(pageIndex, isParent) {
        console.info("userlogapgin._showPage...");
        var $scope = isParent ? this : this.$parent;

        if (pageIndex < 1 || pageIndex > $scope.pagin.pageCnt || $scope.pagin.pageIndex == pageIndex) {
            return;
        } else {
            $scope.pagin.pageIndex = pageIndex;

            $scope.showPage(pageIndex);
            initShowPage($scope);
        }
    }



    function initPagin($scope) {
        $scope.pagin.pageCnt = parseInt($scope.pagin.recordCnt / $scope.pagin.pageSize) + ($scope.pagin.recordCnt % $scope.pagin.pageSize == 0 ? 0 : 1);
    }


    ngApp.directive("userlogPagin", function() {
        return {
            'restrict': 'E',
            'replace': false,
            templateUrl: "userlog/directive/userlog-pagin/view/userlog-pagin.html",
            controller: function($scope, $element) {
                console.info("userlog pagin controller...");
                $scope._range = _range;
                $scope._showPage = _showPage;

                $scope.$watch('pagin', function(newValue, oldValue) {
                    console.info("watch userlog pagin....");
                    if (newValue.recordCnt !== oldValue.recordCnt) {
                        initPagin($scope);
                        initShowPage($scope);
                    }
                }, true);//false不监视引用，true为全等监视，会监视引用
            }
        };
    });

})();